package com.example.demo.contoller;

import com.example.demo.config.CommonConstants;
import com.example.demo.model.JsonData;
import com.example.demo.utils.CommonUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * http接口
 *
 */
@RestController
@RequestMapping("/api/v1/captcha")
public class TestController {

    /**
     * 生成验证码所需
     */
    @Autowired
    private Producer producer;
    /**
     * redisc操作对象
     */
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        //获取自定义配置的验证码
        String captchaText = producer.createText();
        //存入到redis中
        String key = getCaptchaKey(request);
        redisTemplate.opsForValue().set(key,captchaText, CommonConstants.CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        //生成图像返回
        //输出流
        ServletOutputStream out = null;
        try{
            BufferedImage image = producer.createImage(captchaText);
            out = response.getOutputStream();
            ImageIO.write(image,"jpg",out);
            out.flush();
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 验证图片验证码，成功 发送短信验证码
     * @param toPhone 接收验证码的手机号
     * @param imageCode 图片验证码
     * @param request 用于获取redis的key
     * @return
     */
    @GetMapping("send_code")
    @ResponseBody
    public JsonData sendVerificationCode(@RequestParam("phone_number") String toPhone,
                                         @RequestParam("image_code") String imageCode,
                                         HttpServletRequest request){
        //获取Key
        String key = getCaptchaKey(request);
        //从redis中获取值 与传入的imageCode进行比对，成功发送短信验证码
        String redisCode = (String)redisTemplate.opsForValue().get(key);
        if(imageCode != null && imageCode.equalsIgnoreCase(redisCode)){
            //发送短息逻辑之后补充
            return JsonData.buildSuccess();
        }
        return JsonData.buildError("图片验证码错误");
    }

    /**
     * 获取key 通过ip
     * @param request
     * @return
     */
    public String getCaptchaKey(HttpServletRequest request){
        String ipAdd = CommonUtil.getIpAdd(request);
        String header = request.getHeader("user-agent");
        String key = "user:service:" + CommonUtil.MD5(ipAdd + header);
        return key;
    }
}
